from flask import Flask, render_template, session, redirect, url_for, flash, jsonify
from flask import request
from flask import make_response
from flask_script import Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_script import Shell
from flask_migrate import Migrate, MigrateCommand
import os
import urllib.request
import urllib
import re,json
from urllib.error import URLError, HTTPError

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess str'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(basedir,'data.splite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)



class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String())
    users = db.relationship('User',backref='role')

    def __repr__(self):
        return '<Role %r>' %self.name

class User(db.Model):
    __tablename = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64),unique=True,index=True)
    role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
    def __repr__(self):
        return '<User %r>' %self.username

class NameForm(Form):
    name = StringField('what is your name', validators=[Required()])
    submit = SubmitField('Submit')

def make_shell_context():
    return dict(app=app,db=db,User=User, Role=Role)

manager.add_command("shell", Shell(make_context=make_shell_context))

@app.route('/',methods=['GET','POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            session['known']=False
        else:
            session['known']=True
        session['name']=form.name.data
        form.name.data=''
        return redirect(url_for('index'))

    return render_template('howler.html')
    return render_template('index.html',form=form,name=session.get('name'),known=session.get('known',False))


# @app.route('/',methods=['GET','POST'])
# def index():
#     name = None
#     form = NameForm()
#     if form.validate_on_submit():
#         name = form.name.data
#         form.name.data = ''
#     return render_template('index.html',form=form,name=name)
# @app.route('/')
# def index():
#     response = make_response('<h1>This doc carries a cookie</h1>')
#     response.set_cookie('answer','42')
#     return render_template('index.html', current_time = datetime.utcnow())

@app.route('/user/<name>')
def user(name):
    return render_template('user.html',name = name)

@app.route('/music')
def music():
    return render_template('howl.html')

@app.route('/angtest1')
def angtest():
    return render_template('ngbooks.html')

@app.route('/search/<name>',methods=['GET','POST'])
def search(name):
    url = "https://api.douban.com/v2/book/search?q=" + name

    try:
        data = urllib.request.urlopen(url).read()
        data = data.decode('utf-8')
        print("douban-----------" + str(data))
        # weatherJSON = json.JSONDecoder().decode(str(data))
        # print("json" + weatherJSON)
    except HTTPError as e:
        print("douban-----------" + str(e.code))
        print(e.reason)
        return ""


    return str(data)
    # return jsonify({'count':100})

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'),404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'),500

if __name__ == '__main__':
    manager.run()
    # app.run(debug=True)